//
//  BasicClassViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/1.
//

#import "BasicClassViewController.h"
#import "BasicClassListCell.h"
#import <PDFKit/PDFKit.h>
#import "ExamPaperGrammarManager.h"
#import "ExamPaperGrammarModel.h"

@interface BasicClassViewController()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UITableView *leftTableView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,assign)NSInteger sel_index;
@property(nonatomic,strong)PDFView *pdfView;
@property(nonatomic,strong)ExamPaperGrammarManager *grammarManager;
@property(nonatomic,assign)CGFloat w80;
@property(nonatomic,strong)UIView *footerView;

@end

@implementation BasicClassViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(ExamPaperGrammarManager *)grammarManager{
    if(!_grammarManager){
        _grammarManager = [[ExamPaperGrammarManager alloc]init];
        _grammarManager.delegate = self;
    }
    return _grammarManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    _sel_index = 0;
    [self createUI];
    
    [self loadData];
   
}

#pragma mark - 获取语法数据
-(void)loadData{
    self.grammarManager.grade = self.grade;
    [self.grammarManager loadData];
}

-(void)createUI{
    
    [self.customNavigationBar setTitle:self.titleStr];
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat w80 = [DeviceUtils getAdaptedWidthForDesignWidth:80 andCurrentAvailableWidth:self.currentAvailableWidth];
    self.w80 = w80;
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,w80,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.rowHeight = 54;
    self.leftTableView.bounces = NO;
    self.leftTableView.backgroundColor = KbgColor;
    [self.leftTableView registerClass:NSClassFromString(@"BasicClassListCell") forCellReuseIdentifier:@"BasicClassListCell"];
    self.leftTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.leftTableView];
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0,0,w80,kBottomJGH)];
    footerView.backgroundColor = KbgColor;
    self.leftTableView.tableFooterView = footerView;
    self.footerView = footerView;
    
    // 创建PDFView实例
    self.pdfView = [[PDFView alloc]initWithFrame:CGRectMake(w80+12,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-w80-24,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT)];
    self.pdfView.backgroundColor = [UIColor whiteColor];
    self.pdfView.pageShadowsEnabled = NO;
    [self.view addSubview:self.pdfView];
     
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat w80 = [DeviceUtils getAdaptedWidthForDesignWidth:80 andCurrentAvailableWidth:self.currentAvailableWidth];
            self.w80 = w80;
            self.leftTableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,w80,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            self.footerView.frame = CGRectMake(0,0,w80,kBottomJGH);
            self.leftTableView.tableFooterView = self.footerView;
            [self.leftTableView reloadData];
            self.pdfView.frame = CGRectMake(w80+12,kYM_NAVIGATIONBAR_HEIGHT, self.currentAvailableWidth-w80-24,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            [self adjustPDFViewHeight];
            
        });
    }
}

#pragma mark - 加载pdf文件
-(void)loadPDF{
    
    if(self.sel_index < self.dataArr.count){
        self.pdfView.hidden = YES;
        ExamPaperGrammarModel *model = self.dataArr[self.sel_index];
        NSURL *pdfURL = [NSURL URLWithString:model.path];
        PDFDocument *pdfDocument = [[PDFDocument alloc] initWithURL:pdfURL];
        self.pdfView.document = pdfDocument;
        self.pdfView.autoScales = YES;
        // 调整 PDFView 的高度
        [self adjustPDFViewHeight];
        // 延迟显示 PDFView
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.pdfView.hidden = NO; 
        });
    }else{
        self.pdfView.hidden = YES;
    }
}

- (void)adjustPDFViewHeight {
    if (self.pdfView.document) {
        // 获取PDF文档的页数
        NSUInteger pageCount = self.pdfView.document.pageCount;
        CGFloat totalHeight = 0.0;

        // 遍历每一页，计算总高度
        for (NSUInteger i = 0; i < pageCount; i++) {
            PDFPage *page = [self.pdfView.document pageAtIndex:i];
            CGRect pageRect = [page boundsForBox:kPDFDisplayBoxMediaBox];

            // 计算当前页的缩放比例和高度
            CGFloat scale = self.pdfView.bounds.size.width / pageRect.size.width;
            CGFloat pageHeight = pageRect.size.height * scale;

            // 累加所有页面的高度
            totalHeight += pageHeight;
        }

        // 限制总高度不超过屏幕可用高度
        CGFloat maxHeight = self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-24;
        CGFloat finalHeight = MIN(totalHeight, maxHeight);

        // 设置PDFView的高度
        CGRect pdfViewFrame = self.pdfView.frame;
        pdfViewFrame.size.height = finalHeight;
        self.pdfView.frame = pdfViewFrame;

        // 设置显示模式
        self.pdfView.autoScales = YES;
        self.pdfView.displayMode = kPDFDisplaySinglePageContinuous;
        self.pdfView.displayDirection = kPDFDisplayDirectionVertical;

        // 确保第一页显示在顶部
        [self.pdfView goToPage:[self.pdfView.document pageAtIndex:0]];
    }
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BasicClassListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BasicClassListCell"];
    if(indexPath.section < self.dataArr.count){
        ExamPaperGrammarModel *model = self.dataArr[indexPath.section];
        cell.title = model.name;
    }
    if(indexPath.section == _sel_index){
        cell.isSel = YES;
    }else{
        cell.isSel = NO;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.w80,10)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,0,self.w80,20)];
    [footerView addSubview:bgView];
    if(section == _sel_index){
        footerView.backgroundColor = [UIColor whiteColor];
        bgView.backgroundColor = KbgColor;
        [bgView addRoundedCorners:UIRectCornerTopRight withRadii:CGSizeMake(10, 10)];
    }else{
        if((_sel_index > 0)&&(section == _sel_index-1)){
            bgView.frame = CGRectMake(0,-10,self.w80,20);
            footerView.backgroundColor = [UIColor whiteColor];
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
        }else{
            footerView.backgroundColor = KbgColor;
            bgView.backgroundColor = KbgColor;
            [bgView addRoundedCorners:UIRectCornerAllCorners withRadii:CGSizeMake(0,0)];
        }
    }
    footerView.clipsToBounds = YES;
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10.0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.w80,0.00001)];
    headerView.backgroundColor = KbgColor;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _sel_index = indexPath.section;
    [self.leftTableView reloadData];
    [self loadPDF];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.grammarManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamPaperGrammarModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.leftTableView reloadData];
        [self loadPDF];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
    
}

@end
